<?php

namespace App\Http\Middleware;

use App\Models\DoctorDetail;
use App\Models\UserBase;
use App\User;
use Closure;
use RongCloud;

class RongToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $phone = $request->input('phone');

        $users = UserBase::select('id', 'rong_token', 'name', 'type', 'account')
            ->where('phone', '=', $phone)
            ->get();

        if (!$users) {
            abort(400, '用户不存在！');
        }
        foreach ($users as $key => $value) {
            $pic = $this->getPic($value);
            //如果融云token为空  生成token
            if (empty($pic)) {
                $pic = "http://www.rongcloud.cn/images/logo.png";
            }
            $this->newRongToken($value, $pic);
        }


        return $next($request);

    }


    //判断用户融云token是否存在不存在则生成
    protected function newRongToken(UserBase $user, $pic)
    {

        $rong = new RongCloud(config('app.rongcloud_appKey'), config('app.rongcloud_appSecret'));


        //如果不存在生成融云token
        if ($user->type == 1) {
            $ry_account = 'patient_' . $user->account;
        } else {
            $ry_account = 'doctor_' . $user->account;
        }

        //用户名为空时，用ry_token 代替

        $name = $ry_account;
        if ($user->name) {
            $name = $user->name;
        }
        $result = $rong
            ->user()
            ->getToken($ry_account, $name, $pic);

        $result = json_decode($result);

        if ($result->code == 200) {
            $user->rong_token = $result->token;
            $res = $user->save();

            if (!$res) {
                return $result->token;
            }
        }

        return $user->rong_token;
    }

    //判断用户是医生还是患者  获取头像

    protected function getPic($user)
    {
        $pic = '';
        if ($user->type == 1) {

            $patient = \DB::table('tn_patient')
                ->where('ACCOUNT', '=', $user->account)
                ->first();
            if($patient){
                $pic = $patient->PIC;
            }
        } else {
            $doctor = DoctorDetail::where('ACCOUNT', '=', $user->account)
                ->first();
            if($doctor){
                $pic = $doctor->PIC;
            }

        }

        return $pic;
    }
}
